<template>
  <div class="chat-wrapper">
    <v-header :title="chatObject.nickname"></v-header>
    <scroll ref="scroll" :list="chatMsgList" :style="{height: mainHeight + 'px'}" @click.native="$refs.inputWrapper.$el.blur()" style="overflow: hidden;">
      <ul class="message">
        <li v-for="msg in chatMsgList" :key="msg.id" :class="msg.type">
          <p class="time" v-if="msg.sendTimeStr !== ''"> <span>{{msg.sendTimeStr}}</span></p>
          <div class="main">
            <img v-lazy="msg.headUrl" class="avatar"/>
            <div class="text" v-html="msg.content"></div>
          </div>
        </li>
      </ul>
    </scroll>
    <div class="bottom" ref="bottom">
      <div style="display: flex">
        <div class="input" :style="{width: inputWidth + 'px'}">
          <editable-div v-model="inputContent" :canEdit="true" @focus.native="contentFocus" ref="inputWrapper"></editable-div>
          <i @click.stop="toggoleEmotion" class="fa fa-smile-o emoji" aria-hidden="true"></i>
        </div>
        <p class="send" @click="sendMessage">发送</p>
      </div>
      <emotion-grid v-show="showEmotion" @clickEmotion="clickEmotion"></emotion-grid>
    </div>
  </div>
</template>

<script>
import { localUser } from '@/assets/js/local'
import { isIphoneX, isIOS } from '@/assets/js/brower'
import axios from '@/api/axiosApi'

import VHeader from '@/components/v-header/v-header'
import Scroll from '@/components/scroll/scroll'
import EditableDiv from './editableDiv'
import EmotionGrid from './emotionGrid'
import { WechatEmotion as Emotion } from 'vux'
import { mapGetters, mapMutations } from 'vuex'

export default {
  data () {
    return {
      showEmotion: true,
      mainHeight: '',
      inputContent: ''
    }
  },
  computed: {
    ...mapGetters([
      'JIM', 'chatObject', 'chatMsgList'
    ])
  },
  created () {
    this.inputWidth = window.innerWidth - 55 - 24 - 12
    if (isIphoneX()) {
      this.paddingTop = 75
      this.mainHeight = window.innerHeight - 75 - 45 - 14
    } else {
      this.paddingTop = 60
      this.mainHeight = window.innerHeight - 60 - 45
    }
    window._Android_heightChange = (height, visibleHeight) => {
      const scale = height / window.innerHeight // 1px在移动端所占像素点
      this.mainHeight = window.innerHeight - 60 - 45 - (height - visibleHeight) / scale + 24
      if ((height - visibleHeight) / scale <= 24) {
        this.$refs.inputWrapper.$el.blur()
      }
      this.$nextTick(() => {
        this.$refs.scroll.scroll.refresh()
        this.$refs.scroll.scroll.scrollTo(0, this.$refs.scroll.scroll.maxScrollY)
      })
    }
  },
  mounted() {
    this.scrollToBottom()
  },
  components: {
    EditableDiv, EmotionGrid, VHeader, Scroll, Emotion
  },
  methods: {
    contentFocus (e) {
      if (isIOS()) {
        this.$refs.bottom.style.position = 'fixed'
      }
    },
    scrollToBottom () {
      if (this.$refs.scroll) {
        setTimeout(() => {
          this.$refs.scroll.scroll.refresh()
          this.$refs.scroll.scroll.scrollTo(0, this.$refs.scroll.scroll.maxScrollY)
        }, 200)
      }
    },
    sendMessage () {
      const value = this.inputContent
      this.inputContent = ''
      this.$refs.inputWrapper.$el.focus()
      const _self = this
      const JIM = this.$store.getters.JIM
      const user = localUser.get()
      JIM.sendSingleMsg({
        'target_username': _self.chatObject.id,
        'content': value
      }).onSuccess(function (data) {
        _self.pushChatMsgList({
          id: data.msg_id,
          type: 'to',
          nickname: user.nickname,
          headUrl: user.headUrl,
          content: value,
          contentType: 0,
          sendTime: data.ctime_ms
        })
        axios.post(_self, '/v1/pushAlias', {
          userId: _self.chatObject.id,
          content: `${localUser.get('nickname')}: ${value}`,
          linkUrl: `/user/friends`,
          messageType: 1,
          targetUrl: '/user/messageList'
        })
      }).onFail(function (data) {
        _self.$vux.toast.text('发送失败', 'middle')
      }).onTimeout(function (data) {
        _self.$vux.toast.text('发送超时', 'middle')
      })
    },
    toggoleEmotion () {
      this.showEmotion = !this.showEmotion
    },
    clickEmotion (index) {
      this.inputContent += `<img class="emoji" src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif">`
    },
    ...mapMutations({
      pushChatMsgList: 'PUSH_CHAT_MSG_LIST'
    })
  },
  watch: {
    chatMsgList (newVal, oldVal) {
      newVal.forEach((item, index) => {
        if (this.moment().diff(this.moment(item.sendTime), 'days') <= 1) {
          item.sendTimeStr = this.moment(item.sendTime).format('HH:mm')
        } else {
          item.sendTimeStr = this.moment(item.sendTime).format('YYYY-MM-DD HH:mm')
        }
        if (index > 0) {
          if (this.moment(item.sendTime).diff(this.moment(newVal[index - 1].sendTime), 'minutes') < 4) {
            item.sendTimeStr = ''
          }
        }
      })
      this.scrollToBottom()
    },
    showEmotion (newVal) {
      if (newVal) {
        this.mainHeight = window.innerHeight - this.$refs.scroll.$el.offsetTop - 223 - 43
      } else {
        this.mainHeight = window.innerHeight - this.$refs.scroll.$el.offsetTop - 43
      }
      this.$nextTick(() => {
        this.$refs.scroll.scroll.refresh()
        this.$refs.scroll.scroll.scrollTo(0, this.$refs.scroll.scroll.maxScrollY)
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'

.chat-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $color-background;
  z-index: 101;
  .message {
    padding: 10px 15px;
    list-style: none;
    li {
      margin-bottom: 15px;
      .time {
        margin: 4px 0;
        text-align: center;
        span{
          display: inline-block;
          padding: 4px 18px;
          font-size: 13px;
          color: #fff;
          border-radius: 2px;
          background-color: #dcdcdc;
          line-height: 1;
        }
      }
      .avatar {
        float: left;
        width: 40px;
        height: 40px;
        margin: 0 10px 0 0;
        border-radius: 3px;
      }
      .text {
        display: inline-flex;
        position: relative;
        padding: 3px 10px;
        max-width: calc(100% - 100px);
        min-height: 30px;
        line-height: 1.8;
        font-size: 15px;
        text-align: left;
        word-break: break-all;
        background-color: #ffffff;
        border-radius: 4px;
        align-items: center;

        &:before {
          content: " ";
          position: absolute;
          top: 9px;
          right: 100%;
          border: 6px solid transparent;
          border-right-color: #ffffff;
        }
      }
    }
    .to {
      text-align: right;
      .avatar {
        float: right;
        margin: 0 0 0 10px;
      }
      .text {
        background-color: #b2e281;
        &:before {
          right: inherit;
          left: 100%;
          border-right-color: transparent;
          border-left-color: #b2e281;
        }
      }
    }
  }

  .bottom {
    position: relative;
    bottom: 0px;
    left: 0;
    right: 0;
    padding: 5px 12px;
    background: #eee;
    border-top: 1px solid $color-border-3;
    background: #ffffff;

    .input {
      position: relative;
      padding: 3px 40px 3px 7px;
      border-radius: 3px;
      border: 1px solid $color-border-4;
    }

    .send {
      width: 55px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border-radius: 3px;
      background: $color-theme-3;
      color: #fff;
      font-size: 16px;
      margin-left: 12px;
    }

    .emoji {
      position: absolute;
      top: 3px;
      right: 9px;
      font-size 26px;
      color: $color-border-1
    }
  }
}
</style>
<style>
/* .chat-wrapper .message .text img {
  max-width: 50%;
  margin: 7px;
} */

.chat-wrapper .message .text .emoji img {
  width: 24px;
  height: 24px;
  max-width: 24px;
  margin: -1px 0 0 0;
}
</style>

